from flask import Flask, request, session, redirect, send_from_directory
import os



def auth():
    if request.path.startswith("/static") or request.path.startswith("/image/"):
        # 继续向后执行，不拦截静态资源和图片
        return

    if request.path == '/login':
        # 继续向后执行，不拦截
        return

    # 读取cookie &解密获取用户信息
    user_info = session.get('user_info')
    if user_info:
        # 继续向后执行，不拦截
        return
    return redirect('/login')


def get_real_name():
    user_info = session.get('user_info')
    return user_info['real_name']


def create_app():
    app = Flask(__name__)  # 定义模版文件路径
    app.secret_key = 'shfadjfahdjfadksakjdf'

    from .views import account
    from .views import order
    from .views import usart

    app.register_blueprint(account.ac)
    app.register_blueprint(order.od)
    app.register_blueprint(usart.us)


    # 添加图片路由
    @app.route('/image/<path:filename>')
    def serve_image(filename):
        return send_from_directory(os.path.join(app.root_path, 'image'), filename)

    app.before_request(auth)
    app.template_global()(get_real_name)

    return app
